/**
 * 数量框输入
 */
import baseBehavior from '../utils/baseBehavior'
import authorize from '../../js/modules/authorize.js'
const componentBehavior = require('../../js/common/ComponentBehavior')

import {
  api,
  util
} from '../../js/util';
import { calculation } from '../../js/common/math';
const app = getApp()
Component({
  behaviors: [baseBehavior, componentBehavior],
  externalClasses: ['wux-class', 'wux-input-class'],
  lifetimes: {
    attached() {},
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  properties: {
    //传入基础单位对应最小数量
    min: {
      type: Number,
      value: 0,
      observer(newVal, oddVal) {
        if (newVal != oddVal)
          this.valueChange();
      }
    },
    //传入基础单位对应最大数量
    max: {
      type: Number,
      value: 999999,
      observer(newVal, oddVal) {
        if (newVal != 0 && newVal != oddVal)
          this.valueChange();
      }
    },
    //是否默认库存
    isDefaultStock: {
      type: Boolean,
      value: true
    },
    //是否需要初始检测
    isInitTest: {
      type: Boolean,
      value: false
    },
    /**最小值允许为0 */
    minAllowZero: {
      type: Boolean,
      value: true
    },
    /**转换后的最小值 */
    translated_min: {
      type: Number,
      value: 0,
    },
    /**转换后的最大值 */
    translated_max: {
      type: Number,
      value: 999999,
    },
    //转换比率
    translated: {
      type: Number,
      value: 1,
      observer(newVal) {
        this.valueChange();
      }
    },
    //单位
    unit: {
      type: String,
      value: "件"
    },
    step: {
      type: Number,
      value: 1,
    },
    //传入值
    value: {
      type: Number,
      value: -1,
      observer(newVal, oddVal) {
        if (newVal != this.data._real_value) {
          this.valueChange();
        }
      }
    },
    number: {
      type: Number,
      value: 0,
    },
    //小数位数
    quantityDigits: {
      type: Number,
      value: 0
    },
    //是否限制输入数字类型
    isLimitInputType: {
      type: Boolean,
      value: true
    },
    applay: {
      type: Boolean,
      value: false
    },
    //索引
    idx: {
      type: Number,
      value: 0
    },
    unitIndex: {
      type: Number,
      value: 0
    },
    //是否可编辑
    isAdd: {
      type: Boolean,
      value: true
    },
    //主键
    primaryKey: {
      type: String,
      value: ""
    },
    multipleBuy: {
      type: Number,
      value: 0
    },
    //狂点时是否延迟冒泡
    delay: {
      type: Boolean,
      value: true
    },
    //状态-优惠套餐 
    cartType: {
      type: Number,
      value: 0
    },
    //显示input
    iptType: {
      type: Boolean,
      value: true
    },
    limit: { // 用于存储计算后的限制信息，最大值/最小值，原最大值（特价商品超限加购需要）
      type: Object,
      value: {},
    },
  },
  data: {
    isChanged: false,
    init_timeout: null,
    _real_value: 0, //转换后的真实值
    _record_pre_input: 0, //记录输入前的值
    _isInput: false, //是否处于输入状态
    mainColor: api.titleColor || "#e56b14", //主题色
    activeInput: false, // 是否显示input
  },
  submit_timeout: null, //提交定时器
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {}
  },
  methods: {
    /**
     * 获得最值最小值
     */
    getMaxMinValue() {
      if (this.data.max == 0 && this.data.isDefaultStock) {
        this.data.max = 999999;
      }
      let {
        translated,
        quantityDigits,
        isLimitInputType,
        multipleBuy
      } = this.data;
      quantityDigits = translated == 1 ? quantityDigits : (isLimitInputType ? 0 : quantityDigits);
      var str_max = "",
        str_min = "";

      if (this.data.translated != 1) {
        str_max = (this.data.max / this.data.translated).toString();
        this.data.translated_max = this.data.applay ? this.fomatFloat(str_max, quantityDigits) : this.validateDigits(str_max, quantityDigits);
        //辅助单位最小值有小数时必须向上
        //str_min = (this.data.min / this.data.translated).toString();
        this.data.translated_min = util.keepDecimal("ceil", this.data.min / this.data.translated, quantityDigits)
      } else {
        this.data.translated_max = this.data.max;
        this.data.translated_min = this.data.min;
      }
      var translated_min = this.data.translated_min;
      var translated_max = this.data.translated_max;
      if (multipleBuy > 0) {
        // 倍数购买时，最大值要为倍数购买的最大值，如库存10，倍数为3，那么最多只能购买9
        // 最小值同理
        // 计算时改为精确计算，防止浮点数运算问题
        let temp1 = calculation(translated_min, '/', multipleBuy)
        temp1 = Math.ceil(temp1)
        temp1 = calculation(temp1, '*', multipleBuy)
        translated_min = temp1
        let temp2 = calculation(translated_max, '/', multipleBuy)
        temp2 = Math.floor(temp2)
        temp2 = calculation(temp2, '*', multipleBuy)
        translated_max = temp2
      }
      // 将计算后的最大值和最小值放入data，便于键盘组件使用
      this.setData({
        translated_min: translated_min,
        translated_max: translated_max
      })
      return {
        translated_min: translated_min,
        translated_max: translated_max
      }
    },
    /**
     * 获得属于
     */
    getPropertity(_real_value) {
      var that = this;
      var config_value = that.getMaxMinValue();
      var translated_min = config_value.translated_min;
      var translated_max = config_value.translated_max;
      var isAdd = this.data.isAdd;
      let {
        translated,
        quantityDigits,
        isLimitInputType
      } = this.data;
      quantityDigits = translated == 1 ? quantityDigits : (isLimitInputType ? 0 : quantityDigits);

      _real_value = _real_value == undefined ? this.data._real_value : _real_value;
      that.setData({
        isInitTest: false
      })
      // 最小值
      if (_real_value < translated_min && _real_value > 0 && isAdd) {
        _real_value = translated_min;
        that.setData({
          isInitTest: true
        })
      }
      // 最大值
      if (_real_value > translated_max && isAdd) {
        _real_value = translated_max;
        that.setData({
          isInitTest: true
        })
      }
      _real_value = this.data.applay ? this.fomatFloat(_real_value.toString(), quantityDigits) : this.validateDigits(_real_value.toString(), quantityDigits);

      let disabledMin = _real_value <= translated_min,
        disabledMax = _real_value >= translated_max

      return {
        _value: this.data.applay ? this.fomatFloat(_real_value.toString(), quantityDigits) : this.validateDigits(_real_value.toString(), quantityDigits),
        disabledMin,
        disabledMax
      }

    },
    /**
     * 属性值发生变化
     */
    valueChange() {
      var that = this;
      if (that.data.init_timeout) {
        clearTimeout(that.data.init_timeout);
      }
      let v = that.data.value;
      this.data.init_timeout = setTimeout(() => {
        // 倍数精度错误  2020-9-16日注释
        // let {multipleBuy}=this.data;
        // if(multipleBuy>0){
        //   v= Math.ceil(v/multipleBuy)*multipleBuy;
        // }

        that.setData({
          _real_value: v
        });
        that.updateValues(v, function (obj) {
          //当文体框的值》最大值时，自动更新
          if (obj.isInitTest) {
            that.triggerEvent("onNumChage", obj);
          }
        });
      }, 300);
    },
    /**
     * 更新文本框值
     * @param {*} 数字 
     * @param {*} callback 回调函数
     */
    updateValues(_real_value, callback) {
      var that = this;
      let {
        _value,
        disabledMin,
        disabledMax
      } = this.getPropertity(_real_value);
      // 更新数值，判断最小或最大值禁用 sub 或 add 按钮
      this.setData({
        _real_value: _value,
        value: _value,
        disabledMin,
        disabledMax
      }, function () {
        if (callback && typeof (callback) == "function") {
          callback(that.data);
        };
      })
    },

    /**
     * 当按下按键时触发
     * @param {*} type 类型
     */
    onPressButtonEvent(type, meta) {
      let {
        _isInput
      } = this.data;
      var p = {};
      if (_isInput) {
        p = this.onComfirmCancelValue(type);
      } else {
        p = this.onAddSubValue(type);
      }

    },
    /**
     * 当加减框变化时
     * @param {*} type 类型
     */
    onAddSubValue(type) {
      var that = this;
      let {
        translated_max,
        translated_min
      } = this.getMaxMinValue();
      let {
        _real_value,
        step,
        multipleBuy,
        unit,
        minAllowZero,
        quantityDigits
      } = this.data;
      if (multipleBuy > 0) {
        step = multipleBuy;
      }

      var v = 0;
      if (typeof (_real_value) == "string") {
        _real_value = Number(_real_value);
      }
      if (type === 'add') {
        if (translated_max < translated_min) {
          util.tips("未满足最小起订量");
          return false;
        }
        if (translated_max < _real_value) {
          util.tips("已达到最大限购数量");
          return false;
        }
        //加的时候，当前值小于最小值时，将最小值赋值给当前值
        if (translated_min > (_real_value + step)) {
          v = translated_min;
          util.tips(`最少可购买${translated_min}${unit}`);
        } else {
          v = Number(util.formatFloat(_real_value + step, quantityDigits));

          // console.log(v,'=======');
        }

      } else {
        //当咸1时，当前值小于最小值时，将当前值赋值为0
        if ((_real_value - step) < translated_min) {
          v = 0;
        } else {
          v = Number(util.formatFloat(_real_value - step, quantityDigits));
        }
      }
      if (v < 0) {
        v = 0;
      }
      if (v == _real_value) return; //没有变化直接返回
      //不允许为0的情况，如购物车不能减少到0
      if (!minAllowZero && v == 0) {
        if (_real_value > translated_min && translated_min > 0) {
          v = translated_min;
        } else {
          v = _real_value;
          return;
        }

      }
      let p = this.getRealValue(v, unit);
      this.setData({
        _real_value: p._value,
        _isInput: false,
        value: p._value,
        disabledMin: p.disabledMin,
        disabledMax: p.disabledMax
      }, function () {
        if (that.data.delay) {
          if (that.submit_timeout) {
            clearTimeout(that.submit_timeout);
          }
          that.submit_timeout = setTimeout(() => {
            that.triggerEvent("onNumChage", that.data)
          }, 500);
        } else {
          that.triggerEvent("onNumChage", that.data)
        }
      });
    },
    /**
     * 获得真实的值
     * @param {} v 
     */
    getRealValue(v) {
      var that = this;
      let {
        unit,
        minAllowZero
      } = that.data;
      let p = that.getPropertity(v);
      let _value = p._value,
        disabledMin = p.disabledMin,
        disabledMax = p.disabledMax;
      if (disabledMax && _value != v) {
        v = _value;
        util.tips("已达到最大数量：" + _value + unit);
      } else if (disabledMin && _value != v && v > 0) {
        //允许为0才置为0
        if (minAllowZero && _value > v) {
          v = 0;
        } else {
          v = _value;
        }
      } else {
        v = _value;
      }
      return {
        _value: v,
        disabledMin,
        disabledMax
      }
    },
    /**
     * 获得确认取消时文本框的值
     * @param {*} type 类型
     */
    onComfirmCancelValue(type) {
      var that = this;
      let {
        _real_value,
        _record_pre_input,
        minAllowZero,
        translated_min,
        multipleBuy,
        unit
      } = this.data
      if (type === 'sub') { //取消时，原还
        this.setData({
          _real_value: _record_pre_input,
          _isInput: false
        });
        return;
      }
      if (multipleBuy > 0) {
        _real_value = Math.ceil(_real_value / multipleBuy) * multipleBuy;
      }
      let p = this.getPropertity(_real_value);
      let v = _real_value,
        _value = p._value,
        disabledMin = p.disabledMin,
        disabledMax = p.disabledMax;
      //如果达到最小购买数量，则类型变成sub
      if (disabledMin) {
        type = "sub";
      }
      if (type === 'add') {
        if (disabledMax && _value != v) {
          v = _value;
          util.tips("已达到最大数量：" + _value + unit);
        }
      } else if (type === 'sub') {
        if (disabledMin && _value != v && v > 0) {
          v = _value;
        }

      }
      //没有变化直接返回
      if (v == _record_pre_input) {
        this.setData({
          _real_value: _record_pre_input,
          _isInput: false
        });
        return;
      };
      //不允许为0的情况，如购物车不能减少到0
      if (!minAllowZero && v == 0) {
        if (v > translated_min && translated_min > 0) {
          v = translated_min;
        } else {
          this.setData({
            _real_value: _record_pre_input,
            _isInput: false
          });
          return;
        }

      }

      this.setData({
        _real_value: v,
        _isInput: false,
        value: v,
        disabledMin,
        disabledMax
      }, function () {
        that.triggerEvent("onNumChage", this.data);
      });

    },
    /**
     * 获得焦点
     */
    bindfocus(e) {
      //如果为多单规格时，则直接通知弹出
      let data = this.data;
      if (!data.isAdd) {
        this.triggerEvent("onNumChage", this.data);
        return false;
      }
      this.setData({
        _record_pre_input: this.data._real_value,
        _isInput: true
      })
    },
    /**
     * 离开事件，如果文本框为空，则还原为还来的值 
     * */
    bindblur(e) {},
    /**
     * 当键盘输入时，触发 input 事件
     */
    bindinput(e) {
      var that = this;
      let {
        quantityDigits,
        isLimitInputType,
        translated,
        _real_value
      } = this.data;
      var str = e.detail.value;
      str = str.replace(/^0+([1-9]+\d*)/, "$1");
      quantityDigits = translated == 1 ? quantityDigits : (isLimitInputType ? 0 : quantityDigits);
      if (str == "") return;

      if (quantityDigits > 0 && str.indexOf(".") == (str.length - 1)) return;
      if (quantityDigits > 0 && str.charAt(str.length - 1) == '0' && Number(str) == _real_value) return;
      this.setData({
        _real_value: this.data.applay ? this.fomatFloat(str, quantityDigits) : this.validateDigits(str, quantityDigits)
      });
    },
    fomatFloat(src, pos) {
      return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
    },
    /**
     * 
     * @param {*} str 要验证的数字
     * @param {*} quantityDigits 小数位数
     */
    validateDigits(str, quantityDigits) {
      if (!/^([1-9]\d*|[1-9]\d*\.\d*|0\.\d*[1-9]\d*)$/.test(str)) return 0;
      var reg = /^(\d*)/;
      if (quantityDigits > 0) {
        var regstr = "^([1-9]\\d*\\.\\d{0," + quantityDigits + "}|0\\.\\d{0," + quantityDigits + "}|[1-9]\\d*)";
        reg = new RegExp(regstr);

      }
      var rs_match = str.match(reg);
      if (rs_match && rs_match.length > 1) {
        str = rs_match[1];
      }
      //if (rs_match==null) str="0";
      return Number(str);
    },

    /**
     * 手指触摸后，超过350ms再离开
     */
    bindlongpress(e) {
      let {
        type
      } = e.currentTarget.dataset
      let {
        longpress
      } = this.data
      if (longpress) {
        this.onPressButtonEvent(type, true)
      }
    },
    /**
     * 手指触摸后马上离开
     */
    bindtap(e) {
      const {
        type
      } = e.currentTarget.dataset
      const longpress = this.data;
      if (!longpress || longpress && !this.timeout) {
        //是否计算文本框中的数量
        if (longpress.isAdd) {
          this.onPressButtonEvent(type, false);
        }

        if (!longpress.isAdd) {
          this.triggerEvent("onNumChage", this.data);
        }
      }
      if (e.edit) {
        this.setData({
          activeInput: false
        })
      }
    },

    /**
     * 	手指触摸动作结束
     */
    bindtouchend(e) {
      if (this.timeout) {
        clearTimeout(this.timeout)
        this.timeout = null
      }
    },
    /**
     * 手指触摸动作被打断，如来电提醒，弹窗
     */
    touchcancel(e) {
      if (this.timeout) {
        clearTimeout(this.timeout)
        this.timeout = null
      }
    },
    btnAll() {
    },
    /**
     * 显示input
     */
    showInput() {
      //判断是否登录
      if (!authorize.isLogin('store')) {
        authorize.redirect('store');
        return;
      }
      this.setData({
        activeInput: true
      })
    },
    /**
     * 直接输入input内容
     */
    input (e) {
      this.bindinput(e)
    },
    /**
     * input失去焦点
     * @param {*} e 
     */
    blur (e) {
      this.setData({
        _isInput: true
      })
      e.edit = true
      this.bindtap(e) 
    },
    nothing () {
      return false
    }
  },
})